02. Code Checkpoint: Make a FakeDataSource

L5 P2 A08 Make A FakeDataSource V2

In this step, you're going to create a FakeDataSource test double. This will be so that we can properly unit test DefaultTasksRepository.

Optional Step: Download the Code (Code Checkpoint)

If you haven't been following along or want to download the code up to this point, you can do so now. Download the code here, download a zip of the code here, OR you can clone the Github repository for the code:

$ git clone https://github.com/udacity/android-testing.git
$ cd android-architecture
$ git checkout end_codelab_1

Step 1: Create the FakeDataSource Class

In this step you are going to create a class FakeDataSouce, which will be a test double of a LocalDataSource and RemoteDataSource.

  1. In the test source set, right click select New -> Package.
  2. Make a data package with a source package inside.
  3. Create a new class called FakeDataSource in the data/source package:

Step 2: Implement DataSource interface

  1. Make a FakeDataSource class that implements TasksDataSource:

FakeDataSource.kt

class FakeDataSource : TasksDataSource {

}

Android Studio will complain that you haven't implemented required method for TasksDataSource.

  1. Use the Quick-fix menu and select Implement members.

  1. Select all of the methods and press OK:

Step 3: Implement the getTasks method in FakeDataSource

Start by writing fake version of these methods:

  • Write getTasks: If tasks isn't null, you should return a Success result. If tasks is null, then you should return an Error result.
  • Write deleteAllTasks: clear the mutable tasks list.
  • Write saveTask: add the task to the list.

Here's the final code for these methods:

FakeDataSource.kt

override suspend fun getTasks(): Result<List<Task>> {
    tasks?.let { return Success(ArrayList(it)) }
    return Error(
        Exception("Tasks not found")
    )
}


override suspend fun deleteAllTasks() {
    tasks?.clear()
}

override suspend fun saveTask(task: Task) {
    tasks?.add(task)
}

This is similar to how the actual local and remote data sources work. You'll implement the rest of this class later, but let's write a test!